import { Injectable } from '@nestjs/common';
import { Roles } from '@/modules/roles/roles.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateRoleDto } from '@/modules/roles/create-role.dto';
import { UpdateRoleDto } from '@/modules/roles/update-role.dto';

@Injectable()
export class RolesService {
  constructor(
    @InjectRepository(Roles)
    private readonly rolesRepository: Repository<Roles>,
  ) {}

  async create(createRoleDto: CreateRoleDto) {
    const role = await this.rolesRepository.create(createRoleDto);
    console.log('role', role);
    return this.rolesRepository.save(role);
  }

  findAll() {
    return this.rolesRepository.find();
  }

  findOne(id: number) {
    return this.rolesRepository.findOne({ where: { id } });
  }

  async update(id: number, updateRoleDto: UpdateRoleDto) {
    const role: Roles = await this.findOne(id) as Roles;
    const newRole = this.rolesRepository.merge(role, updateRoleDto);
    return this.rolesRepository.update(id, newRole);
  }

  remove(id: number) {
    // delete 可以根据id进行删除，并且不会触发生命周期函数
    // remove 需要根据实例去删除，并且会触发生命周期函数
    return this.rolesRepository.delete(id);
  }
}
